import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:winkai/entity/vip_product_info.dart';
import 'package:winkai/ext/ext.dart';
import 'package:winkai/ext/screen_ext.dart';
import 'package:winkai/helper/iap/iap_helper.dart';
import 'package:winkai/res/dimens.dart';
import 'package:winkai/ui/vip/controller/vip_controller.dart';
import 'package:winkai/utils/image_utils.dart';
import 'package:winkai/utils/net_image_load_utils.dart';
import 'package:winkai/utils/page_jump_utils.dart';
import 'package:winkai/widget/custom_style_bg.dart';

class VipPage extends StatefulWidget {
  const VipPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _VipPageState();
  }
}

class _VipPageState extends State<VipPage> {
  final controller = Get.put(VipController());

  @override
  void initState() {
    super.initState();
    var from = Get.arguments;
    eventBus.on<VipOpenEvent>().listen((event) {
      if (mounted) {
        // reportEvent('suc_sub_${event.productId}_${widget.from.name}');
        Get.back();
      }
    });
    controller.loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GetBuilder<VipController>(builder: (_) {
        var bottomPadding = navigationHeight;
        return AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle.light,
          child: Stack(
            children: [
              _buildBannerWidget(),
              Column(
                children: [
                  SizedBox(height: 148.w + statusHeight),
                  Expanded(
                    child: Container(
                      decoration: const BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            Color(0x00000000),
                            Color(0x4d000000),
                            Color(0x80000000),
                            Color(0xb3000000),
                            Color(0xb3000000),
                            Color(0xb3000000),
                            Color(0xb3000000),
                            Color(0xCC000000),
                          ],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: Column(
                      children: [
                        SizedBox(height: 148.w + statusHeight),
                        _buildVipEquity(),
                        ..._buildVipPackageWidget(),
                        SizedBox(height: 52.w),
                        _buildBottomWidget(),
                        SizedBox(height: 12.w),
                        Container(
                          width: double.infinity,
                          padding: EdgeInsets.symmetric(
                              horizontal: Dimens.mainHorizontalSpacing),
                          child: Text(
                            'vip_desc'.tr,
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: const Color(0x80ffffff),
                              fontWeight: FontWeight.w300,
                            ),
                          ),
                        ),
                        SizedBox(
                          height:
                              bottomPadding > 0 ? bottomPadding + 20.w : 20.w,
                        )
                      ],
                    ),
                  )
                ],
              ),
              _buildTitleBar(),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildBannerWidget() {
    var width = screenWidth;
    var height = screenHeight;
    return SizedBox(
      width: width,
      height: height,
      child: controller.banners.isNotEmpty
          ? CarouselSlider.builder(
              options: CarouselOptions(
                height: height,
                viewportFraction: 1,
                aspectRatio: 1,
                enableInfiniteScroll: true,
                autoPlay: true,
                autoPlayInterval: const Duration(seconds: 3),
                onPageChanged: (index, reason) {},
              ),
              itemCount: controller.banners.length,
              itemBuilder: (BuildContext context, int index, int realIndex) {
                return NetImageLoadUtils.load(
                    controller.banners[index], width, height);
              },
            )
          : null,
    );
  }

  Widget _buildTitleBar() {
    return SafeArea(
      left: false,
      bottom: false,
      right: false,
      child: Container(
        height: 48.w,
        padding: EdgeInsets.symmetric(horizontal: Dimens.mainHorizontalSpacing),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            GestureDetector(
              onTap: () {
                Get.back();
              },
              child: ImageUtils.getImage('ic_ai_back', 36.w, 36.w),
            ),
            GestureDetector(
              onTap: () {
                controller.restorePurchases();
              },
              child: CustomStyleBg(
                height: 28.w,
                borderRadius: 24.w,
                color: Colors.white,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                child: Text(
                  'vip_restore'.tr,
                  style: TextStyle(
                    fontSize: 13.sp,
                    color: Colors.black,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVipEquity() {
    Widget item(String name) {
      return Row(
        children: [
          ImageUtils.getImage('ic_ai_subsribe_arrow1', 14.w, 14.w),
          SizedBox(width: 4.w),
          Expanded(
            child: Text(
              name,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ),
        ],
      );
    }

    return Padding(
      padding: EdgeInsets.only(
        top: 10.w,
        left: Dimens.mainHorizontalSpacing,
        right: Dimens.mainHorizontalSpacing,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: double.infinity,
            child: Text(
              'vip_upgrade'.tr,
              style: TextStyle(
                fontSize: 32.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
          SizedBox(height: 8.w),
          item('vip_intro1'.tr),
          SizedBox(height: 2.w),
          item('vip_intro2'.tr),
          SizedBox(height: 2.w),
          item('vip_intro3'.tr),
          SizedBox(height: 2.w),
          item('vip_intro4'.tr),
          SizedBox(height: 2.w),
        ],
      ),
    );
  }

  List<Widget> _buildVipPackageWidget() {
    Widget buildItem(
      VipProductInfo item, {
      GestureTapCallback? onTap,
    }) {
      var isSelect = item == controller.currentSelect;
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.mainHorizontalSpacing),
        child: GestureDetector(
          onTap: onTap,
          behavior: HitTestBehavior.translucent,
          child: SizedBox(
            width: double.infinity,
            height: 72.w,
            child: Stack(
              alignment: Alignment.topRight,
              children: [
                Container(
                  width: double.infinity,
                  height: 72.w,
                  padding: EdgeInsets.symmetric(horizontal: 14.w),
                  alignment: Alignment.centerLeft,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      color: !isSelect ? const Color(0x40808080) : null,
                      border: isSelect
                          ? Border.all(
                              width: 2.w,
                              color: const Color(0xffDFFF32),
                            )
                          : Border.all(
                              width: 2.w,
                              color: Colors.transparent,
                            )),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Row(
                              children: [
                                Flexible(
                                  child: Text(
                                    item.name,
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                                if (item.saveRate.isNotEmpty)
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular(20.w),
                                        color: const Color(0xffDFFF32)),
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 8.w, vertical: 0.8.w),
                                    margin: EdgeInsets.only(left: 4.w),
                                    child: Text(
                                      'vip_discount'
                                          .trParams({'number': item.saveRate}),
                                      style: TextStyle(
                                        fontSize: 11.sp,
                                        color: Colors.black,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                            Row(
                              children: [
                                Text(
                                  item.price,
                                  style: TextStyle(
                                    fontSize: 20.sp,
                                    fontWeight: FontWeight.w700,
                                    color: Colors.white,
                                  ),
                                ),
                                SizedBox(width: 4.w),
                                Expanded(
                                  child: Text(
                                    'vip_hour_price'
                                        .trParams({'price': item.hourPrice}),
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500,
                                      color: const Color(0xb3ffffff),
                                    ),
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 28.w,
                  height: 28.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: isSelect
                          ? const Color(0xffDFFF32)
                          : const Color(0x66ffffff),
                      borderRadius: const BorderRadius.only(
                          topRight: Radius.circular(16),
                          bottomLeft: Radius.circular(16))),
                  child: ImageUtils.getImage(
                      isSelect
                          ? 'ic_ai_subsribe_arrow2'
                          : 'ic_ai_subsribe_arrow3',
                      16.w,
                      16.w),
                )
              ],
            ),
          ),
        ),
      );
    }

    List<Widget> vipPackageWidgetList = [];
    for (var value in controller.vipProductList) {
      if (vipPackageWidgetList.isEmpty) {
        vipPackageWidgetList.add(SizedBox(height: 24.w));
      } else {
        vipPackageWidgetList.add(SizedBox(height: 12.w));
      }
      vipPackageWidgetList.add(buildItem(value, onTap: () {
        controller.currentSelect = value;
        setState(() {});
      }));
    }
    return vipPackageWidgetList;
  }

  Widget _buildBottomWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (controller.vipProductList.isNotEmpty) _buildSubscribeVipWidget(),
        SizedBox(height: 12.w),
        _buildVipRuleTips(),
        const SizedBox(height: 4),
        _buildProtocolWidget(),
      ],
    );
  }

  Widget _buildSubscribeVipWidget() {
    return GestureDetector(
      onTap: () {
        controller.subscribeVip();
      },
      child: Container(
        width: double.infinity,
        height: 48.w,
        margin: EdgeInsets.symmetric(horizontal: Dimens.mainHorizontalSpacing),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            color: const Color(0xffDFFF32)),
        alignment: Alignment.center,
        child: Text(
          'vip_continue'.tr,
          style: TextStyle(
            fontSize: 17.sp,
            color: Colors.black,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Widget _buildVipRuleTips() {
    return SizedBox(
      width: double.infinity,
      child: Text(
        'vip_rule_tips'.tr,
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 10.sp,
          color: const Color(0x4dffffff),
          fontWeight: FontWeight.w300,
        ),
      ),
    );
  }

  Widget _buildProtocolWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        GestureDetector(
          onTap: () {
            PageJumpUtils.toPrivacyPolicyPage();
          },
          child: Text(
            'vip_privacy'.tr,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 10.sp,
              color: const Color(0xccffffff),
              fontWeight: FontWeight.w300,
            ),
          ),
        ),
        Container(
          width: 0,
          height: 10.w,
          margin: EdgeInsets.symmetric(horizontal: 26.w),
          color: Colors.transparent,
        ),
        GestureDetector(
          onTap: () {
            PageJumpUtils.toTermOfUsePage();
          },
          child: Text(
            'vip_terms'.tr,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 10.sp,
              color: const Color(0xccffffff),
              fontWeight: FontWeight.w300,
            ),
          ),
        ),
      ],
    );
  }
}
